# -*- coding: utf-8 -*-
import os
import arcpy

fc_layer_name = arcpy.GetParameterAsText(0)
year = int(arcpy.GetParameterAsText(1))
src_ID = arcpy.GetParameterAsText(2)
target_ID = arcpy.GetParameterAsText(3)
csv_fullpath_filename = arcpy.GetParameterAsText(4)
cell_size = arcpy.GetParameter(5)


# work_path = "G:/DataForDoctorPaper/博士论文数据.gdb"
# arcpy.env.workspace = work_path
# input_fc = "RasterUnitsV4_2003"
# year = 2003
# src_ID = "OBJECTID"
# target_ID = "# GeoID"
# csv_fullpath_filename = r"h:\tt\raster_logistic_V4_2003.csv"
# cell_size = 90

# Step 1： 将处理单元点和预测结果，通过ID列连接起来
# 由于management.AddJoin的第一个参数为图层，而不是要素类。因此先要通过MakeFeatureLayer_management方法创建一个要素图层。
#代码模式下，由于input_fc是要素类，需要转化为layer图层。在ArcGIS Pro中直接执行不需要
# fc_layer_name = input_fc
# arcpy.MakeFeatureLayer_management(input_fc,  fc_layer_name)

# 添加连接的帮助文档地址：http://pro.arcgis.com/zh-cn/pro-app/tool-reference/data-management/add-join.htm
arcpy.management.AddJoin(fc_layer_name, src_ID, csv_fullpath_filename, target_ID, "KEEP_ALL")
print("\nAdd Join successful!\n")

# Step 2: 将连接后的结果进行栅格化，（Feature to Raster）
csv_base_name = os.path.basename(csv_fullpath_filename)
value_field = "{0}.Prob_{1}".format(csv_base_name, year)
output_raster_name = "{0}_result".format(csv_base_name[0:-4])
# arcpy.AddMessage(os.path.realpath(output_raster_name))
# print(value_field)
# print(output_raster_name)
output_raster_fullpath = "{0}/{1}".format(arcpy.env.workspace, output_raster_name)
arcpy.AddMessage(output_raster_fullpath)

# 执行要素转栅格
if arcpy.Exists(output_raster_fullpath):
    arcpy.Delete_management(output_raster_fullpath)
arcpy.conversion.FeatureToRaster(fc_layer_name,
                               value_field,
                               output_raster_fullpath,
                               cell_size)

# arcpy.conversion.PointToRaster(fc_layer_name,
#                                value_field,
#                                output_raster_fullpath,
#                                "MOST_FREQUENT",
#                                "NONE",
#                                cell_size)
# arcpy.AddMessage("\nPoint to Raster Conversion success!\n")
